package com.example.mypplication.sortlist.newsortlist


import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ImageView
import android.widget.TextView
import androidx.recyclerview.widget.RecyclerView
import com.example.mypplication.R

class SortAdapter(
    private var list: List<SortModel>
) : RecyclerView.Adapter<SortAdapter.ViewHolder>() {

    var isNeedCheck = false
        set(value) {
            field = value
            notifyDataSetChanged()
        }

    private var onItemClickListener: ((SortModel) -> Unit)? = null

    fun setOnItemClickListener(listener: (SortModel) -> Unit) {
        onItemClickListener = listener
    }

    fun updateList(newList: List<SortModel>) {
        list = newList
        notifyDataSetChanged()
    }

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
        val view = LayoutInflater.from(parent.context)
            .inflate(R.layout.item, parent, false)
        return ViewHolder(view)
    }

    override fun onBindViewHolder(holder: ViewHolder, position: Int) {
        val item = list[position]

        // Show/hide section header
        val section = getSectionForPosition(position)
        if (position == getPositionForSection(section)) {
            holder.tvLetter.visibility = View.VISIBLE
            holder.tvLetter.text = item.sortLetters
        } else {
            holder.tvLetter.visibility = View.GONE
        }

        // Handle checkbox visibility
        if (isNeedCheck) {
            holder.checked.visibility = View.VISIBLE
            holder.checked.setImageResource(
                if (item.isChecked) R.drawable.round_checked else R.drawable.round_unchecked
            )
        } else {
            holder.checked.visibility = View.GONE
        }

        holder.tvTitle.text = item.name
        holder.sex.setImageResource(if (item.sex == 0) R.drawable.boy else R.drawable.girl)

        holder.itemView.setOnClickListener {
            onItemClickListener?.invoke(item)
        }
    }

    override fun getItemCount() = list.size

    fun getSectionForPosition(position: Int): Int = list[position].sortLetters[0].toInt()

    fun getPositionForSection(section: Int): Int {
        for (i in list.indices) {
            val sortStr = list[i].sortLetters
            val firstChar = sortStr[0].uppercaseChar()
            if (firstChar.toInt() == section) {
                return i
            }
        }
        return -1
    }

    class ViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
        val tvTitle: TextView = itemView.findViewById(R.id.tv_user_item_name)
        val tvLetter: TextView = itemView.findViewById(R.id.catalog)
        val checked: ImageView = itemView.findViewById(R.id.iv_user_item_check)
        val sex: ImageView = itemView.findViewById(R.id.iv_user_item_sex)
    }
}